const util = require('util')
const { User } = require('../models/user')
const { generateToken } = require('../../core/util')
const { Auth } = require('../../middlewares/auth')
const axios = require('axios')

class WXManager{
    static async codeToToken(code){
        const url = util.format(global.config.wx.loginUrl,
            global.config.wx.appid,
            global.config.wx.appsecret,
            code
        )
        const res = await axios.get(url)
        if(res.status !== 200){
            throw new global.errs.AuthFailed(['openid获取失败'])
        }

        if(!res.data.openid){
            throw new global.errs.AuthFailed(['openid获取失败'])
        }

        // console.log(res)

        let user = await User.getUserByOpenid(res.data.openid)
        if(!user){
            user = await User.registerByOpenid(res.data.openid)
        }
        // 微信账号过期时间
        let expires_in = res.data.expires_in;

        return generateToken(user.id, Auth.USER,expires_in)
    }
}

module.exports = {
    WXManager
}